package com.opener.common.utils;

import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 *
 * @author baboy
 * @date 22/08/2017
 */
public class ImageUtils {
    public static boolean createThumbnail(String fp, String destFp,String destExt, int destWidth, int destHeight){
        File f = new File(fp);
        BufferedImage buffer = null;
        try {
            buffer = ImageIO.read(f);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        /*
         * 核心算法，计算图片的压缩比
         */
        int w = buffer.getWidth();
        int h =buffer.getHeight();
        double ratioX= (double)destWidth/w;
        double ratioY= (double)destHeight/h;

        double ratio = ratioX > ratioY ? ratioX : ratioY;

        /*
         * 对于图片的放大或缩小倍数计算完成，ratiox大于1，则表示放大，否则表示缩小
         */
        AffineTransform tf = AffineTransform.getScaleInstance(ratio, ratio);
        AffineTransformOp op = new AffineTransformOp(tf, null);
        buffer = op.filter(buffer, null);
        //从放大的图像中心截图
        buffer = buffer.getSubimage((buffer.getWidth()-destWidth)/2, (buffer.getHeight() - destHeight) / 2, destWidth, destHeight);
        try {
            File destFile = new File(destFp);
            if (destExt == null || destExt.equals("")){
                int i = destFp.lastIndexOf(".");
                if (i>0 && (i+1) < destFp.length()){
                    destExt = destFp.substring(i+1);
                }
            }
            if (destExt == null || destExt.equals("")){
                destExt = "jpg";
            }

            ImageIO.write(buffer, destExt, destFile);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public static void main(String[] args){
        createThumbnail("/Users/baboy/Desktop/test.jpg","/Users/baboy/Desktop/test.copy.jpg",null, 100,190);
    }
}
